package com.colter.project.sample.thread.part07.test1;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//基于优先级的Executor
public class Test3 {
	public static void main(String[] args) {
		ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, 1, TimeUnit.SECONDS,
				new PriorityBlockingQueue<Runnable>());
		for (int i = 0; i < 4; i++) {
			MyPriorityTask task = new MyPriorityTask(i, "name" + i);
			executor.execute(task);
		}

		try {
			TimeUnit.MICROSECONDS.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		for (int i = 4; i < 8; i++) {
			MyPriorityTask task = new MyPriorityTask(i, "name" + i);
			executor.execute(task);
		}

		executor.shutdown();
		try {
			executor.awaitTermination(1, TimeUnit.HOURS);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Main:End");
	}
}

class MyPriorityTask implements Runnable, Comparable<MyPriorityTask> {
	private int priority;
	private String name;

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public MyPriorityTask(int priority, String name) {
		super();
		this.priority = priority;
		this.name = name;
	}

	@Override
	public int compareTo(MyPriorityTask o) {
		if (this.priority < o.priority) {
			return 1;
		} else if (this.priority > o.priority) {
			return -1;
		}
		return 0;
	}

	@Override
	public void run() {
		System.out.println("MyPriorityTask:" + name + " " + priority);
		try {
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String toString() {
		return "MyPriorityTask [priority=" + priority + ", name=" + name + "]";
	}

}
